package com.sopt.friends.sub;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sopt.friends.R;
import com.sopt.friends.db.FriendsDBHelper;
import com.sopt.friends.db.Constants.FriendsDB;
import com.sopt.friends.http.HttpManager;
import com.sopt.friends.http.MsgListManager;
import com.sopt.friends.http.MsgManager;
import com.sopt.friends.statics.FriendsStaticVars;
import com.sopt.friends.util.FriendsChatManager;
import com.sopt.friends.vo.FriendsChat;
import com.sopt.friends.vo.FriendsCommonItem;
import com.sopt.view.ChatListAdapter;
import com.sopt.view.HomeMenuAdapter;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SubChatList extends Activity{
	private HttpManager httpMananger;
    private MsgManager msgManager;
    private MsgListManager msgListManager;
    private Context mContext;
    private String myNumber;
    
    private SendMessageSetObserver sObserver = new SendMessageSetObserver();
    
    private String currentTargetUser;
    private String targetNumber;
    private FriendsChatManager chatManager;
    private ListView chatViewList;
    
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chatlist);
		mContext = this;
		chatManager = new FriendsChatManager(this, getContentResolver());
		ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		boolean isWifiAvail = ni.isAvailable();
		boolean isWifiConn = ni.isConnected();
		ni = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean isMobileAvail = ni.isAvailable();
		boolean isMobileConn = ni.isConnected();
		
		if(isWifiConn){
			Log.v("changdoc", "INTERNET AVALIBLE!!!+_+");
		}else if(isMobileConn){
			chatManager.showToast(getResources().getString(R.string.userFeeComment));
		}else{
			chatManager.showToast(getResources().getString(R.string.cannotUseInternet));
        	finish();	
		}
        
		targetNumber = getIntent().getExtras().getString("number");
		currentTargetUser = getIntent().getExtras().getString("name");
		
		TextView textView = (TextView)findViewById(R.id.currentTargetMember);
		
		textView.setText("To : " + currentTargetUser);
		
        
        
    	msgManager = MsgManager.getInstance(this);
    	msgListManager = new MsgListManager();
    	
    	httpMananger = HttpManager.getInstance(this); 
    	
    	Button btnSend = (Button)findViewById(R.id.btnSendMessage);
    	btnSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				sendMessage();
			}
		});
    	
    	getMyMessageList();
	}
	
	private void updateChatVewList() {
		chatViewList = (ListView)findViewById(R.id.listChat);
		
		ArrayList<FriendsChat> infoMenuList = chatManager.getChatListByNumber(targetNumber);
		
		ChatListAdapter infomenuAdapter = new ChatListAdapter(SubChatList.this, R.layout.row_chat_list, infoMenuList);

		chatViewList.setAdapter(infomenuAdapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		updateChatVewList();
	}
	
	protected void sendMessage(){
    	EditText et = (EditText)findViewById(R.id.editTextMessage);
    	
    	if(et.getText().toString().length()>0 && !msgManager.isLoading()){
    		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        	imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
        	
    		TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            myNumber = mTelephonyMgr.getLine1Number();
            
            et.setEnabled(false);
            
			try {
				msgManager.load(FriendsStaticVars.HOST_URL+FriendsStaticVars.ACTION_SEND_MSG+"?content="
						+URLEncoder.encode(et.getText().toString(), "UTF-8")
						+"&number="+myNumber
						+"&relative_number="+targetNumber);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
			toggleLoadingStatus();
			
			if(msgManager.isLoading())msgManager.addObserver(sObserver);
    	}else if(msgManager.isLoading()){
    		alert("전송중입니다.");
    	}else{
    		alert("글자를 입력해주세요");
		}
	}
	
	public void toggleLoadingStatus(){
		if (httpMananger.isLoading() || msgManager.isLoading()) {
        	setProgressBarIndeterminateVisibility(httpMananger.isLoading() || msgManager.isLoading());
        }else{
        	setProgressBarIndeterminateVisibility(false);
        }
	}
	
	public void alert(String msg){
		if(msg.length()>0)Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}
	
	    
    private class SendMessageSetObserver extends DataSetObserver {
        public void onChanged() {
        	toggleLoadingStatus();
        	
        	JSONObject json = new JSONObject(msgManager.get(msgManager.size()-1));
        	
        	try {
				String content = json.getString("CONTENT");
				if(content.length()>0 && chatManager.insertChatNew(targetNumber, content)){
					alert(getResources().getString(R.string.toastSaveComplete));
				}
			} catch (JSONException e) {
				alert(getResources().getString(R.string.toastError));
			}
			EditText et = (EditText)findViewById(R.id.editTextMessage);
			et.setText("");
			et.setEnabled(true);
        	
        	msgManager.clear();
        	
        	updateChatVewList();
        }
        public void onInvalidated() {
        }
    }
    
    protected void getMyMessageList(){
    	
    		TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String myNumber = mTelephonyMgr.getLine1Number();

            JSONArray json =  msgListManager.getMsgList(FriendsStaticVars.HOST_URL+FriendsStaticVars.ACTION_GET_MSG_LIST+"?number="+myNumber);
            if(json!=null){
        	for(int i = 0; i<json.length();i++){
	        	JSONObject curJson;
				try {
					curJson = json.getJSONObject(i);
	        	String curNum =curJson.getString("MEMBER_NUMBER");
				FriendsDBHelper dbhelper = new FriendsDBHelper(mContext);
				
				String curContent = curJson.getString("CONTENTS_TEXT");
				String curRegdate = curJson.getString("CONTENTS_REGDATE");
				ContentValues values = new ContentValues();
				values.put(FriendsDB.CHAT_CONTENT, curContent);
				values.put(FriendsDB.PHONE_NUMBER, curNum);
				values.put(FriendsDB.CHAT_REGDATE, curRegdate);
				SQLiteDatabase db = dbhelper.getWritableDatabase();
				db.insert(FriendsDB.TABLE_CHAT, null, values);
				db.close();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.v("changdoc",e.getLocalizedMessage());
				}
        	}
			
			alert(getResources().getString(R.string.toastSaveComplete));
			EditText et = (EditText)findViewById(R.id.editTextMessage);
			et.setText("");
			et.setEnabled(true);
			
        	updateChatVewList();
            }
    	
    }
    

    
}
